<template>
  <el-dialog
    :title="dialogType === 'add' ? 'Add Organization' : 'Edit Organization'"
    v-model="dialogVisible"
    width="700px"
    :close-on-click-modal="false"
    @closed="handleDialogClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="180px"
      label-position="right"
    >
      <div>
        <h3 class="mb-4">Organization Info</h3>
        <el-form-item label="Organization type:" prop="organizationType">
          <el-select
            v-model="form.organizationType"
            placeholder="Please choose"
            style="width: 100%"
          >
            <el-option label="Installer" :value="1" />
            <el-option label="Distributor" :value="2" />
            <!-- 排除Zendure(0)和组织类客户(3)，只允许安装商(1)和经销商(2) -->
          </el-select>
        </el-form-item>

        <el-form-item label="Organization name:" prop="organizationName">
          <el-input
            v-model="form.organizationName"
            placeholder="Please enter"
            :maxlength="100"
            :show-word-limit="true"
          />
        </el-form-item>

        <el-form-item label="Country/Region:" prop="countryRegion">
          <el-select
            v-model="form.countryRegion"
            placeholder="Please choose"
            style="width: 100%"
          >
            <el-option label="Germany" value="Germany" />
            <el-option label="France" value="France" />
            <el-option label="Australia" value="Australia" />
            <el-option label="Netherlands" value="Netherlands" />
            <el-option label="Sweden" value="Sweden" />
          </el-select>
        </el-form-item>

        <el-form-item label="Organization address:" prop="organizationAddr">
          <el-input
            v-model="form.organizationAddr"
            placeholder="Please enter"
            :maxlength="200"
            :show-word-limit="true"
          />
        </el-form-item>

        <el-form-item label="Organization E-mail:" prop="organizationEmail">
          <el-input
            v-model="form.organizationEmail"
            placeholder="Please enter"
            :maxlength="100"
            :show-word-limit="true"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>

        <el-form-item label="Note:" prop="note">
          <el-input
            v-model="form.note"
            type="textarea"
            :rows="4"
            placeholder="Please enter"
            :maxlength="200"
            :show-word-limit="true"
          />
        </el-form-item>
      </div>

      <div>
        <h3 class="mt-6 mb-4">Administrator Info</h3>
        <el-form-item label="User name:" prop="adminName">
          <el-input
            v-model="form.adminName"
            placeholder="Please enter"
            :maxlength="100"
            :show-word-limit="true"
          />
        </el-form-item>

        <el-form-item label="User E-mail:" prop="adminEmail">
          <el-input
            v-model="form.adminEmail"
            placeholder="Please enter"
            :maxlength="100"
            :show-word-limit="true"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>

        <el-form-item label="User phone number:" prop="adminPhone">
          <el-input
            v-model="form.adminPhone"
            placeholder="Please enter"
            :maxlength="20"
            :show-word-limit="true"
            @input="handleAdminPhoneInput"
          />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="flex justify-end">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">Submit</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
// 下级组织编辑对话框
// 职责：
// - 录入组织与管理员基础信息
// - 新增/编辑时的字段与校验管理
// - 校验通过后向父组件回传数据
import { ref, reactive, watch, nextTick } from "vue";
import type { FormInstance, FormRules } from "element-plus";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  dialogType: {
    type: String,
    default: "add" // 'add' 或 'edit'
  }
});

const emit = defineEmits(["update:visible", "submit-success"]);

// 表单实例与显隐
const formRef = ref<FormInstance>();
const dialogVisible = ref(props.visible);

// 表单数据
const form = reactive({
  id: "",
  organizationType: undefined as number | undefined,
  organizationName: "",
  countryRegion: "",
  organizationAddr: "",
  organizationEmail: "",
  note: "",
  adminName: "",
  adminEmail: "",
  adminPhone: ""
});

// 动态设置验证规则
const getRules = () => {
  return {
    organizationType: [
      {
        required: true,
        message: "Please select organization type",
        trigger: "change"
      }
    ],
    organizationName: [
      {
        required: true,
        message: "Please enter organization name",
        trigger: "blur"
      },
      {
        max: 100,
        message: "Organization name cannot exceed 100 characters",
        trigger: "blur"
      }
    ],
    countryRegion: [
      {
        required: true,
        message: "Please select country/region",
        trigger: "change"
      }
    ],
    organizationAddr: [
      {
        required: true,
        message: "Please enter organization address",
        trigger: "blur"
      },
      {
        max: 200,
        message: "Organization address cannot exceed 200 characters",
        trigger: "blur"
      }
    ],
    organizationEmail: [
      {
        required: props.dialogType === 'add',
        message: "Please enter organization email",
        trigger: "blur"
      },
      {
        type: "email",
        message: "Please enter a valid email address",
        trigger: ["blur", "change"]
      },
      {
        max: 100,
        message: "Organization email cannot exceed 100 characters",
        trigger: "blur"
      }
    ],
    note: [
      {
        max: 200,
        message: "Note cannot exceed 200 characters",
        trigger: "blur"
      }
    ],
    adminName: [
      {
        required: true,
        message: "Please enter administrator name",
        trigger: "blur"
      },
      {
        max: 100,
        message: "Administrator name cannot exceed 100 characters",
        trigger: "blur"
      }
    ],
    adminEmail: [
      {
        required: true,
        message: "Please enter administrator email",
        trigger: "blur"
      },
      {
        type: "email",
        message: "Please enter a valid email address",
        trigger: ["blur", "change"]
      },
      {
        max: 100,
        message: "Administrator email cannot exceed 100 characters",
        trigger: "blur"
      }
    ],
    adminPhone: [
      {
        required: true,
        message: "Please enter administrator phone number",
        trigger: "blur"
      },
      {
        pattern: /^\d+$/,
        message: "管理员电话号码只能输入数字",
        trigger: "blur"
      },
      {
        max: 20,
        message: "Administrator phone number cannot exceed 20 characters",
        trigger: "blur"
      }
    ]
  };
};

const rules = getRules() as FormRules;

// 监听可见性：父传入 visible 改变时同步对话框显隐
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
  }
);

// 监听对话框可见性：同步回父组件
watch(
  () => dialogVisible.value,
  val => {
    emit("update:visible", val);
  }
);

// 监听传入的表单数据：编辑态回填
watch(
  () => props.formData,
  val => {
    if (Object.keys(val).length > 0) {
      // 重置表单
      Object.assign(form, {
        id: "",
        organizationType: undefined,
        organizationName: "",
        countryRegion: "",
        organizationAddr: "",
        organizationEmail: "",
        note: "",
        adminName: "",
        adminEmail: "",
        adminPhone: ""
      });
      
      // 设置表单数据
      form.id = val.id || "";
      form.organizationType = val.organizationType || undefined;
      form.organizationName = val.organizationName || "";
      form.countryRegion = val.countryRegion || "";
      form.organizationAddr = val.organizationAddr || "";
      form.organizationEmail = val.organizationEmail || "";
      form.note = val.note || "";
      form.adminName = val.adminName || "";
      form.adminEmail = val.adminEmail || "";
      form.adminPhone = val.adminPhone || "";
    }
  },
  { immediate: true, deep: true }
);

// 处理管理员电话号码输入，只允许数字
const handleAdminPhoneInput = (value: string) => {
  // 过滤非数字字符
  const numericValue = value.replace(/\D/g, '');
  form.adminPhone = numericValue;
};

// 提交表单：校验通过后回传数据
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      // 构建提交数据
      let submitData: any = {
        ...form,
        // 区分新增和编辑操作
        isAdd: props.dialogType === "add"
      };
      
      // 编辑时也必须包含 adminEmail 字段，否则会报500错误
      // 下级组织修改要带这个属性,这个属性也不能修改
      
      emit("submit-success", submitData);
    }
  });
};

// 对话框关闭时重置表单
const handleDialogClosed = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  Object.assign(form, {
    id: "",
    organizationType: undefined,
    organizationName: "",
    countryRegion: "",
    organizationAddr: "",
    organizationEmail: "",
    note: "",
    adminName: "",
    adminEmail: "",
    adminPhone: ""
  });
};
</script>
